package git.etl.eval;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import git.etl.ExprParseException;
import git.etl.ExprEvalTask.EetJobD;
import git.etl.eval.IEvaluator.IFunction;
import git.etl.eval.IEvaluator.ILex;

/**
 *  match factor to every element in base
 */
public class FuncJoin
	implements IFunction
{
	@Override
	public Map<List<String>, BigDecimal[]> perform(
			Map<List<String>, BigDecimal[]> base, ILex lex, EetJobD t,
			IEvaluator owner)
		throws Exception
	{
		String w = lex.nextElement();
		if (!"(".equals(w))
			throw new ExprParseException("'('", w);
		
		w = lex.nextElement();
		Map<List<String>, BigDecimal[]> b = owner.resolveSymbol(w, lex, t, base);		
		HashSet<String> si = new HashSet<String>();
		
		while(!")".equals(w = lex.nextElement()))
		{
			if (!",".equals(w))
				throw new ExprParseException(",", w);
			
			w = lex.nextElement();
			si.add(w);
		}
		
		return join(base, b, si);
	}
	
	public static Map<List<String>, BigDecimal[]>join(Map<List<String>, BigDecimal[]> base
		, Map<List<String>, BigDecimal[]> src, HashSet<String> si)
	{
   		Map<List<String>, BigDecimal[]> r = new HashMap<List<String>, BigDecimal[]>();
   		
		for (Map.Entry<List<String>, BigDecimal[]> en : base.entrySet())
		{
			List<String> k = new ArrayList<String>(en.getKey());
			for (int i = 0; i < k.size(); ++i)
			{
				if (!si.contains(String.valueOf(i)) && !"".equals(k.get(i)))
					k.set(i, "");
			}
			r.put(en.getKey(), src.get(k));
		}
   		
		return r;
	}
}
